<template>
  <div class="user-management">
    <!-- 页面标题和统计卡片 -->
    <lay-card>
      <template #header>
        <div class="page-header">
          <h2>用户管理</h2>
          <p>管理系统中的所有用户信息</p>
        </div>
      </template>
      <div class="stats-cards">
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ userStats.totalUsers }}</div>
            <div class="stats-label">总用户数</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ userStats.activeUsers }}</div>
            <div class="stats-label">活跃用户</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ userStats.newUsersToday }}</div>
            <div class="stats-label">今日新增</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ userStats.newUsersThisMonth }}</div>
            <div class="stats-label">本月新增</div>
          </div>
        </lay-card>
      </div>
    </lay-card>

    <!-- 操作区域 - 已注释，管理员不可新增用户 -->
    <!-- <lay-card style="margin-top: 16px;">
      <lay-row :space="16">
        <lay-col :md="24">
          <lay-button type="primary" @click="handleCreate">
            <lay-icon type="layui-icon-add-1" />
            新增用户
          </lay-button>

        </lay-col>
      </lay-row>
    </lay-card> -->

    <!-- 搜索筛选区域 -->
    <lay-card style="margin-top: 16px;">
      <lay-form :model="searchForm" ref="searchFormRef">
        <lay-row :space="16">
          <lay-col :md="6">
            <lay-form-item label="关键词" prop="keyword">
              <lay-input v-model="searchForm.keyword" placeholder="用户名/邮箱/昵称/手机号" />
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="状态" prop="status">
              <lay-select v-model="searchForm.status" placeholder="请选择状态">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="1">正常</lay-select-option>
                <lay-select-option value="0">禁用</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="性别" prop="gender">
              <lay-select v-model="searchForm.gender" placeholder="请选择性别">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="0">未知</lay-select-option>
                <lay-select-option value="1">男</lay-select-option>
                <lay-select-option value="2">女</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>

        </lay-row>
        <lay-row :space="16">
          <lay-col :md="24">
            <lay-form-item>
              <lay-button type="primary" @click="handleSearch">
                <lay-icon type="layui-icon-search" />
                搜索
              </lay-button>
              <lay-button @click="handleReset" style="margin-left: 8px;">
                <lay-icon type="layui-icon-refresh" />
                重置
              </lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>

    <!-- 用户列表 -->
    <lay-card style="margin-top: 16px;">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>用户列表</span>
          <div>
            <lay-button size="sm" @click="handleExport">
              <lay-icon type="layui-icon-export" />
              导出
            </lay-button>
          </div>
        </div>
      </template>

      <lay-table 
        :columns="columns" 
        :data-source="userList" 
        :loading="loading"
        :pagination="false"
        row-key="id"
      >



        <template #gender="{ data }">
          <lay-tag :type="getGenderTagType(data.gender)">
            {{ data.genderText }}
          </lay-tag>
        </template>

        <template #status="{ data }">
          <lay-switch
            :model-value="data.status === 1"
            @update:model-value="(value) => handleStatusChange(data, value)"
            :switch-text="['启用', '禁用']"
          />
        </template>

        <template #balance="{ data }">
          <span class="balance-text">¥{{ data.balance.toFixed(2) }}</span>
        </template>

        <template #lastLoginAt="{ data }">
          <span>{{ formatDate(data.lastLoginAt) }}</span>
        </template>

        <template #createdAt="{ data }">
          <span>{{ formatDate(data.createdAt) }}</span>
        </template>

        <template #operator="{ data }">
          <lay-button size="xs" @click="handleView(data)">查看</lay-button>
          <!-- 已注释，管理员不可编辑用户 -->
          <!-- <lay-button size="xs" type="primary" @click="handleEdit(data)" style="margin-left: 4px;">编辑</lay-button> -->
          <!-- 不需要删除功能 ，因为删除会导致用户数据丢失，影响业务逻辑 暂时先注释掉 -->
          <!-- <lay-button 
            size="xs" 
            type="danger" 
            @click="handleDelete(data)" 
            style="margin-left: 4px;"
          >
            删除
          </lay-button> -->
        </template>
      </lay-table>
      
      <!-- 自定义分页组件 -->
      <Pagination
        :total="pagination.total"
        :page="pagination.current"
        :page-size="pagination.pageSize"
        :page-size-options="pagination.limits"
        @change="handlePaginationChange"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </lay-card>

    <!-- 用户详情/编辑对话框 -->
    <UserDialog
      v-model="userDialogVisible"
      :mode="userDialogMode"
      :user-data="currentUser"
      @success="handleDialogSuccess"
      @manage-address="handleManageAddress"
    />

    <!-- 用户地址管理对话框 -->
    <UserAddressDialog
      :visible="addressDialogVisible"
      :user-id="selectedUserId"
      @update:visible="addressDialogVisible = $event"
      @success="handleAddressDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { layer } from '@layui/layui-vue'
import { UserApi } from '../../api/module/user'
import type { User, UserStatsResponse } from '../../types/user'
import UserDialog from './components/UserDialog.vue'
import UserAddressDialog from './components/UserAddressDialog.vue'
import Pagination from '@/components/Pagination.vue'

// 响应式数据
const loading = ref(false)
const userList = ref<User[]>([])

const userDialogVisible = ref(false)
const userDialogMode = ref<'view' | 'create' | 'edit'>('view')
const currentUser = ref<User | null>(null)

// 地址管理对话框
const addressDialogVisible = ref(false)
const selectedUserId = ref<number>(0)

// 用户统计数据
const userStats = ref<UserStatsResponse>({
  totalUsers: 0,
  activeUsers: 0,
  inactiveUsers: 0,
  newUsersToday: 0,
  newUsersThisWeek: 0,
  newUsersThisMonth: 0,
  genderDistribution: {
    unknown: 0,
    male: 0,
    female: 0
  },
  levelDistribution: {}
})

// 搜索表单
const searchForm = reactive<{
  keyword: string
  status: string
  gender: string
}>({
  keyword: '',
  status: '',
  gender: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showPage: true,
  showCount: true,
  showSkip: true,
  showLimit: true,
  limits: [10, 20, 50, 100]
})

// 表格列配置
const columns = [
  {
    title: '选择',
    width: '60px',
    type: 'checkbox',
    fixed: 'left'
  },
  {
    title: 'ID',
    key: 'id',
    width: '80px'
  },

  {
    title: '用户名',
    key: 'username',
    minWidth: '120px'
  },
  {
    title: '邮箱',
    key: 'email',
    minWidth: '180px'
  },
  {
    title: '手机号',
    key: 'phone',
    minWidth: '120px'
  },
  {
    title: '昵称',
    key: 'nickname',
    minWidth: '100px'
  },
  {
    title: '性别',
    key: 'gender',
    customSlot: 'gender',
    width: '80px'
  },
  {
    title: '状态',
    key: 'status',
    customSlot: 'status',
    width: '80px'
  },
  {
    title: '积分',
    key: 'points',
    width: '80px'
  },
  {
    title: '余额',
    key: 'balance',
    customSlot: 'balance',
    width: '100px'
  },
  {
    title: '最后登录',
    key: 'lastLoginAt',
    customSlot: 'lastLoginAt',
    width: '160px'
  },
  {
    title: '注册时间',
    key: 'createdAt',
    customSlot: 'createdAt',
    width: '160px'
  },
  {
    title: '操作',
    key: 'operator',
    customSlot: 'operator',
    width: '200px',
    fixed: 'right'
  }
]

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const params: any = {
      page: pagination.current,
      limit: pagination.pageSize,
      sortBy: 'id',
      sortOrder: 'DESC'
    }

    // 添加筛选条件
    if (searchForm.keyword) {
      params.keyword = searchForm.keyword
    }
    if (searchForm.status !== '') {
      params.status = searchForm.status
    }
    if (searchForm.gender !== '') {
      params.gender = searchForm.gender
    }
    
    const response = await UserApi.getUserList(params)
    userList.value = response.data.users
    pagination.total = response.data.pagination.total
  } catch (error) {
    layer.msg('获取用户列表失败', { icon: 2 })
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取用户统计信息
const fetchUserStats = async () => {
  try {
    const response = await UserApi.getUserStats()
    userStats.value = response.data
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}



// 分页变化处理
const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page
  pagination.pageSize = pageSize
  fetchUserList()
}

// 页码变化处理
const handlePageChange = (page: number) => {
  pagination.current = page
  fetchUserList()
}

// 每页数量变化处理
const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1 // 重置到第一页
  fetchUserList()
}

// 搜索
const handleSearch = () => {
  pagination.current = 1 // 重置到第一页
  fetchUserList()
}

// 重置搜索条件
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.gender = ''
  pagination.current = 1 // 重置到第一页
  fetchUserList()
}

// 新增用户 - 已注释，管理员不可新增用户
// const handleCreate = () => {
//   currentUser.value = null
//   userDialogMode.value = 'create'
//   userDialogVisible.value = true
// }

// 查看用户
const handleView = (user: User) => {
  currentUser.value = user
  userDialogMode.value = 'view'
  userDialogVisible.value = true
}

// 编辑用户 - 已注释，管理员不可编辑用户
// const handleEdit = (user: User) => {
//   currentUser.value = user
//   userDialogMode.value = 'edit'
//   userDialogVisible.value = true
// }

// 删除用户 - 已注释，管理员不可删除用户
// const handleDelete = async (user: User) => {
//   try {
//     // 确认删除后执行删除操作
//     await UserApi.deleteUser(user.id)
//     layer.msg('删除成功', { icon: 1 })
//     fetchUserList()
//     fetchUserStats()
//   } catch (error) {
//     if (error !== 'cancel') {
//       layer.msg('删除失败', { icon: 2 })
//       console.error('删除用户失败:', error)
//     }
//   }
// }



// 状态变化
const handleStatusChange = async (user: User, newStatus: boolean) => {
  try {
    const status = newStatus ? 1 : 0
    await UserApi.updateUserStatus(user.id, status)
    user.status = status
    user.statusText = status === 1 ? '正常' : '禁用'
    layer.msg('状态更新成功', { icon: 1 })
    fetchUserStats()
  } catch (error) {
    layer.msg('状态更新失败', { icon: 2 })
    console.error('更新用户状态失败:', error)
    // 恢复原状态
    user.status = user.status === 1 ? 0 : 1
  }
}

// 导出
const handleExport = () => {
  layer.msg('导出功能开发中...', { icon: 3 })
}

// 对话框成功回调
const handleDialogSuccess = () => {
  fetchUserList()
  fetchUserStats()
}

// 管理地址
const handleManageAddress = (userId: number) => {
  selectedUserId.value = userId
  addressDialogVisible.value = true
}

// 地址对话框成功回调
const handleAddressDialogSuccess = () => {
  // 地址更新成功后可以做一些处理，比如刷新用户信息
  layer.msg('地址操作成功', { icon: 1 })
}

// 获取性别标签类型
const getGenderTagType = (gender: number) => {
  switch (gender) {
    case 1:
      return 'primary'
    case 2:
      return 'warm'
    default:
      return 'normal'
  }
}

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  fetchUserList()
  fetchUserStats()
})
</script>

<style scoped>
.user-management {
  padding: 16px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}



.balance-text {
  color: #52c41a;
  font-weight: 500;
}
</style>